<?php
declare(strict_types=1);

namespace App\Workers;

use App\Services\YikaoSpecialDetailSpiderService;
use GuzzleHttp\Client;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Workerman\Worker;

class YikaoSpecialDetailSpiderWorker
{
    private Logger $logger;
    private YikaoSpecialDetailSpiderService $spiderService;

    public function __construct()
    {
        // 初始化日志 - 同时输出到文件和控制台
        $this->logger = new Logger('yikao-special-detail-worker');
        
        // 控制台处理器
        $consoleHandler = new \Monolog\Handler\StreamHandler('php://stdout');
        $consoleHandler->setFormatter(new \Monolog\Formatter\LineFormatter(
            "[%datetime%] %level_name%: %message% %context%\n",
            'Y-m-d H:i:s',
            true,
            true
        ));
        $this->logger->pushHandler($consoleHandler);
        $this->logger->pushHandler(new StreamHandler(
            '/www/college/storage/logs/yikao-special-detail-worker.log',
            Logger::DEBUG
        ));

        // 初始化HTTP客户端
        $clientOptions = [
            'timeout' => 30,
            'headers' => [
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
            ],
            // 'proxy' => 'http://host.docker.internal:1082'
            'proxy' => 'http://127.0.0.1:1080'
        ];

        $httpClient = new Client($clientOptions);

        // 初始化采集服务
        $this->spiderService = new YikaoSpecialDetailSpiderService($httpClient, $this->logger);
    }

    public function start(): void
    {
        $this->logger->info('艺考专业详情采集Worker已启动');

        try {
            $majors = $this->spiderService->getSpecialMajors(['id', 'special_id', 'name']);
            $total = count($majors);
            $success = 0;

            $this->logger->info("发现{$total}个待采集的艺术类专业");

            foreach ($majors as $index => $major) {
                $current = $index + 1;
                $this->logger->info("正在处理 {$current}/{$total}: {$major['name']}");

                if ($this->spiderService->crawlSpecialDetail((array)$major)) {
                    $success++;
                }

                // 防止请求过于频繁
                sleep(1);
            }

            $this->logger->info("采集完成。成功: {$success}/{$total}");
        } catch (\Exception $e) {
            $this->logger->error("Worker运行失败: " . $e->getMessage());
        }
    }

    /**
     * 启动Worker
     * @param Worker $worker Worker实例
     * @param array $options 命令行参数
     */
    public static function run(Worker $worker, array $options): void
    {
        $worker->onWorkerStart = function () use ($options) {
            $worker = new self();
            $worker->logger->info('艺考专业详情采集Worker已启动，参数: ' . json_encode($options));
            $worker->start();
        };
    }
}
